package com.quanquan.user.message;

import com.quanquan.user.exception.IntegralException;
import com.quanquan.user.service.IntegralTradingDetailsService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

/**
 * 功能描述:接收积分余额补全信息
 *
 * @ClassName: MqImageReceiver
 * @Author: xiaoqianh丶
 * @Date: 2019-03-13 14:07
 * @Version: V1.0
 */
@Slf4j
@Component
public class MqIntegralBalanceReceiver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    private final IntegralTradingDetailsService integralTradingDetailsService;

    @Autowired
    public MqIntegralBalanceReceiver(IntegralTradingDetailsService imageService) {
        this.integralTradingDetailsService = imageService;
    }

    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "integralBalance",
            durable = "true"),
            exchange = @Exchange(value = "integral.exchange",
            type = "topic"),
            ignoreDeclarationExceptions = "true",
            key = "integralBalance.*")})
    @RabbitHandler
    public void completionIntegralBalance(Message message, Channel channel) throws IOException {
        //积分额度
        String integralBalance = Objects.requireNonNull(message.getHeaders().get("integralBalance")).toString();
        //积分明细id
        String integralDetailsId = Objects.requireNonNull(message.getHeaders().get("integralDetailsId")).toString();
        //手工ack
        long deliveryTag= Long.parseLong(Objects.requireNonNull(message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)).toString());
        channel.basicAck(deliveryTag,false);

        //根据积分明细id查出对应的积分记录
        //补全积分明细余额
        integralTradingDetailsService.updateIntegralBalance(integralDetailsId,integralBalance);
        //结算消费积分3个月的总的积分消费入会时查询
        //查询出他入的所有消费记录拿到消费积分的总数，判断他有没有超10000，如果超了
        try {
            integralTradingDetailsService.countIntegral(integralDetailsId);
        } catch (IntegralException e) {
            e.printStackTrace();
        }
        //入会时间



    }




}
